using System;
using NUnit.Framework;

namespace Solver
{
	/// <summary>
	/// Find the value of d < 1000 for which 1/d contains the longest recurring cycle.
	/// </summary>
	public class Problem026 : SelfChecker, IProblem
	{
		private static readonly int[] Buffer = new int[5000];

		public int Id
		{
			get { return 26; }
		}

		public string Solve()
		{
			return Solve(1000);
		}

		private static string Solve(int n)
		{
			var maxD = 0;
			var maxW = 0;
			for (var d = 1; d < n; d++)
			{
				var w = GetCycleLength(d);
				if (w <= maxW) continue;
				maxW = w;
				maxD = d;
			}
			return maxD.ToString();
		}

		private static int GetCycleLength(int d)
		{
			var r = 1;
			for (var idx = 1; ; ++idx)
			{
				r = (r * 10) % d;
				Buffer[idx] = r;
				if (r == 0) return 0;
				var matchedIdx = Array.IndexOf(Buffer, r);
				if (matchedIdx < idx) return idx - matchedIdx;
			}
		}

		[Test]
		public override void Check()
		{
			Assert.AreEqual("7", Solve(10));
			Assert.AreEqual("983", Solve());
		}
	}
}